﻿using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace CeskyRozhlasWP8.Model
{
    public abstract class AppPersistence
    {
        public static void SaveDataToIsolatedStorage(string isoFileName, string value)
        {
            var isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            var file = isoStore.OpenFile(isoFileName, FileMode.Create);
            var sw = new StreamWriter(file);
            sw.Write(value);
            sw.Close();
        }

        public const string SavedStateFilename = "RecentShowsList.txt";
        public const string SavedStateKey = "ShowsData";

        public static string LoadDataFromIsolateStorage(string isoFileName)
        {
            var isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            if (!isoStore.FileExists(isoFileName))
            {
                return null;
            }
            // This method loads the data from isolated storage, if it is available.
            var sr = new StreamReader(isoStore.OpenFile(isoFileName, FileMode.Open));
            var savedData = sr.ReadToEnd();
            sr.Close();
            return savedData;
        }

        public static void RestoreAppState(ShowsData iShowsData)
        {
            string aSavedState = null;
            if (PhoneApplicationService.Current.State.ContainsKey(SavedStateKey))
            {
                aSavedState = PhoneApplicationService.Current.State[SavedStateKey] as string;
            }
            else
            {
                aSavedState = LoadDataFromIsolateStorage(SavedStateFilename);
            }
            if (aSavedState != null)
            {
                JsonConvert.PopulateObject(aSavedState, iShowsData);
            }
        }

        public static void StoreAppState(ShowsData iShowsData)
        {
            var aSerializedVersion = JsonConvert.SerializeObject(iShowsData);
            PhoneApplicationService.Current.State[SavedStateKey] = aSerializedVersion;
            // Also store it in isolated storage, in case the application is never reactivated.
            SaveDataToIsolatedStorage(SavedStateFilename, aSerializedVersion);
        }
    }
}